package com.rentcars.service.impl;

import com.rentcars.entity.Resource;
import com.rentcars.mapper.ResourceMapper;
import com.rentcars.service.ResourceService;
import com.rentcars.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 肖克
 * @date 2021/3/2 17:59
 */
@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    public List<Resource> getResources(Integer isabled) {
        return resourceMapper.selectAllResources(isabled);
    }

    @Override
    public List<Resource> getResourcesByParentId(String parentid) {
        return resourceMapper.getResourcesByParentId(parentid);
    }

    @Override
    public Resource getResourcesById(String permisid) {
        return resourceMapper.getResourcesById(permisid);
    }

    @Override
    public void delResources(String[] permisid) {
        for (String str : permisid) {
            traverseDel(str);
        }
    }

    @Override
    public String addResource(Resource resource) {
        try {
            //uuid编码随机生成id
            resource.setPermisid(String.valueOf(UuidUtil.getUUIDInOrderId()));
            //获取父节点名称
            Resource parent = resourceMapper.getResourcesById(resource.getParentid());
            resource.setParentids(parent.getPermisname());
            //添加资源权限
            resourceMapper.insert(resource);
        } catch (NullPointerException e) {
            return "未查询到上级编号";
        }
        return null;
    }

    @Override
    public void updateResource(Resource resource) {
        resourceMapper.updateByPrimaryKeySelective(resource);
    }

    /**
     * 遍历删除所有子节点
     *
     * @param parentid
     */
    public void traverseDel(String parentid) {
        List<Resource> resources = resourceMapper.getResourcesByParentId(parentid);
        if (resources.size() != 0) {
            for (Resource resource : resources) {
                traverseDel(resource.getPermisid());
            }
        }
        resourceMapper.deleteByPrimaryKey(parentid);
    }
}
